package com.gao.wechat.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.gao.wechat.service.WechantMessageService;
import com.gao.wechat.util.WeChatHttpUtil;
import com.gao.wechat.vo.CustomMessage;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("wechat/message")
public class WechantController 
{
	
	@Autowired
	private WechantMessageService wechantMessageService;
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		String backUrl="http://gaoyijing.iok.la/wechat/message/wechat/callBack";
        /**
        *这儿一定要注意！！首尾不能有多的空格（因为直接复制往往会多出空格），其次就是参数的顺序不能变动
        **/
        String url =null;
		try
		{
			url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5a5a923b715b1f45"+
			        "&redirect_uri=" + URLEncoder.encode(backUrl,"UTF-8")+
			        "&response_type=code" +
			        "&scope=snsapi_userinfo" +
			        "&state=STATE#wechat_redirect";
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
        response.sendRedirect(url);
	}
	
	/**
	 * 微信回调接口
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/callBack", method = RequestMethod.GET)
	public ModelAndView callBack(HttpServletRequest request, HttpServletResponse response)
	{
		ModelAndView mv = new ModelAndView();
        String code=request.getParameter("code");
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx5a5a923b715b1f45" +
                "&secret=b061923d558ff585c1cf8d2f95c14fc3"+
                "&code=" +code+
                "&grant_type=authorization_code";
        try 
        {
        	JSONObject jsonObject = WeChatHttpUtil.doGetJson(url);
            String openid=jsonObject.getString("openid");
            String token=jsonObject.getString("access_token");
            String infoUrl="https://api.weixin.qq.com/sns/userinfo?access_token=" +token+
                    "&openid=" +openid+
                    "&lang=zh_CN";
            JSONObject userInfo=WeChatHttpUtil.doGetJson(infoUrl);
            System.out.println(userInfo);
            String accessToken = wechantMessageService.getAccessToken(WeChatHttpUtil.APPID, WeChatHttpUtil.APPSECRET);
			CustomMessage cm = new CustomMessage();
			cm.setTouser(openid);
			cm.setMsgtype("text");
			JSONObject json = new JSONObject();
			json.put("content", "12121313");
			cm.setText(jsonObject);
			String data= JSON.toJSONString(cm);
			wechantMessageService.sendCustom(accessToken, data);
            mv.setViewName("redirect:https://www.baidu.com");
        }catch(Exception ex) 
        {
        	ex.printStackTrace();
        }
        return mv;
	}
}
